import { defineStore } from 'pinia'
import { ref } from 'vue'
import { settingsService, notebookService } from '@/services/ipc'
import { UserSettings } from "@/types"

const defaultSettings: UserSettings = {
  general: {
    autoUpdate: true,
    debugMode: false,
    language: 'zh-CN'
  },
  editor: {
    imageStoragePath: 'assets/images',
    defaultNoteType: 'markdown',
    notebookPath: '',  // 将在初始化时设置
    enableMultipleNotes: true,  // 默认允许多开
    maxOpenNotes: 10,          // 最多打开10个笔记
    wrapTabs: true,           // 默认标签换行
    autoSaveInterval: 60,     // 60秒自动保存
    maxHistoryCount: 50,      // 保留最近50条历史记录
    markdownConfig: {
      livePreview: true,
      codeHighlight: true
    }
  },
  sync: {
    enabled: false,
    type: 'none',
    serverUrl: ''
  },
  privacy: {
    fileEncryption: false,
    transmissionEncryption: true,
    timeoutProtection: false,
    timeoutDuration: 30
  },
  appearance: {
    theme: 'auto',
    fontSize: 14,
    fontFamily: 'system-ui',
    colors: {
      primary: '#409EFF',
      secondary: '#909399',
      success: '#67C23A',
      warning: '#E6A23C',
      danger: '#F56C6C',
      info: '#909399'
    },
    background: {
      type: 'color',
      value: '',
      opacity: 1
    }
  }
}

export const useSettingsStore = defineStore('settings', () => {
  // 当前应用的设置
  const settings = ref<UserSettings>({ ...defaultSettings })
  // 未保存的设置
  const storedSettings = ref<UserSettings>({ ...defaultSettings })

  // 初始化设置
  const init = async () => {
    try {
      const savedSettings = await settingsService.loadSettings()
      settings.value = { ...defaultSettings, ...savedSettings }
      storedSettings.value = JSON.parse(JSON.stringify(settings.value))
      applySettings()
    } catch (error) {
      console.error('Failed to load settings:', error)
    }
  }

  // 更新设置（不立即应用）
  const updateSettings = (newSettings: Partial<UserSettings>) => {
    Object.assign(storedSettings.value, newSettings)
  }

  // 应用设置
  const applySettings = async () => {
    // 创建一个纯净的设置对象
    const cleanSettings = JSON.parse(JSON.stringify(storedSettings.value))
    settings.value = cleanSettings

    // 应用主题
    const htmlEl = document.documentElement
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    const theme = settings.value.appearance.theme === 'auto'
      ? (prefersDark ? 'dark' : 'light')
      : settings.value.appearance.theme

    // 设置根元素主题
    htmlEl.setAttribute('data-theme', theme)
    // 设置 Element Plus 主题
    htmlEl.className = theme === 'dark' ? 'dark' : ''

    // 应用其他设置
    htmlEl.style.fontSize = `${settings.value.appearance.fontSize}px`
    htmlEl.style.fontFamily = settings.value.appearance.fontFamily
    htmlEl.setAttribute('lang', settings.value.general.language)

    // 应用颜色
    Object.entries(settings.value.appearance.colors).forEach(([key, value]) => {
      htmlEl.style.setProperty(`--el-color-${key}`, value)
    })

    // 应用背景
    if (settings.value.appearance.background.type === 'color') {
      htmlEl.style.setProperty('--bg-color', settings.value.appearance.background.value)
      htmlEl.style.setProperty('--bg-opacity', settings.value.appearance.background.opacity.toString())
    }

    // 监听系统主题变化
    if (settings.value.appearance.theme === 'auto') {
      window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
        const newTheme = e.matches ? 'dark' : 'light'
        htmlEl.setAttribute('data-theme', newTheme)
        htmlEl.className = e.matches ? 'dark' : ''
      })
    }

    // 保存到数据库
    try {
      await settingsService.saveSettings(cleanSettings)
    } catch (error) {
      console.error('Failed to save settings:', error)
      throw error
    }
  }

  // 重置设置
  const resetSettings = () => {
    storedSettings.value = { ...defaultSettings }
  }

  // 取消编辑
  const cancelEdit = () => {
    storedSettings.value = JSON.parse(JSON.stringify(settings.value))
  }

  // 更新笔记空间位置
  const updateNotebookPath = async (newPath: string) => {
    const oldPath = settings.value.editor.notebookPath

    // 检查原位置是否有笔记
    if (oldPath && await notebookService.hasNotes(oldPath)) {
      // 这里应该由调用者处理确认对话框
      const migrated = await notebookService.migrate(oldPath, newPath)
      if (!migrated) {
        throw new Error('Failed to migrate notes')
      }
    }

    // 更新设置
    await updateSettings({
      editor: {
        ...settings.value.editor,
        notebookPath: newPath
      }
    })
  }

  return {
    init,
    settings,
    storedSettings,
    updateSettings,
    updateNotebookPath,
    applySettings,
    resetSettings,
    cancelEdit
  }
})
